package org.chen.scene.service.task.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.scene.task.GrabTaskLog;
import org.chen.scene.mapper.GrabTaskLogMapper;
import org.chen.scene.service.task.GrabTaskLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GrabTaskLogServiceImpl extends ServiceImpl<GrabTaskLogMapper, GrabTaskLog> implements GrabTaskLogService {
    
    @Autowired
    private GrabTaskLogMapper grabTaskLogMapper;
    
    @Override
    public GrabTaskLog createLog(Long taskId, String cityName, String keywords, Integer pageIndex, Integer pageSize) {
        GrabTaskLog log = new GrabTaskLog();
        log.setTaskId(taskId);
        log.setCityName(cityName);
        log.setKeywords(keywords);
        log.setPageIndex(pageIndex);
        log.setPageSize(pageSize);
        log.setStatus("RUNNING");
        log.setStartTime(LocalDateTime.now());
        log.setCreateTime(LocalDateTime.now());
        
        grabTaskLogMapper.insert(log);
        return log;
    }
    
    @Override
    public void updateLogResult(Long logId, Integer totalCount, Integer newCount, Integer updateCount, String status, String errorMessage) {
        GrabTaskLog log = grabTaskLogMapper.selectById(logId);
        if (log != null) {
            log.setTotalCount(totalCount);
            log.setNewCount(newCount);
            log.setUpdateCount(updateCount);
            log.setStatus(status);
            log.setErrorMessage(errorMessage);
            log.setEndTime(LocalDateTime.now());
            
            // 计算执行耗时
            if (log.getStartTime() != null) {
                log.setExecuteTime(Duration.between(log.getStartTime(), log.getEndTime()).toMillis());
            }
            
            grabTaskLogMapper.updateById(log);
        }
    }
    
    @Override
    public Map<String, Object> getTaskExecuteStats(Long taskId) {
        return grabTaskLogMapper.getTaskExecuteStats(taskId);
    }
    
    @Override
    public List<GrabTaskLog> getRecentLogs(Long taskId, Integer limit) {
        return grabTaskLogMapper.getRecentLogs(taskId, limit == null ? 10 : limit);
    }
}